<template>
  <div class="home-view">
    <DefineTemplate v-slot="{ $slots, data, loading, bodyClass, showMore }">
      <el-card
        v-loading="loading"
        header-class="card-hd"
        :body-class="bodyClass"
        style="
          box-shadow: none;
          border: none;
          border-radius: 4px;
          background: var(--base-bg-color);
        "
      >
        <template #header>
          <div class="h-full flex items-center">
            <div class="flex-1">
              <span class="font-[700]">{{ data.title }}</span>
            </div>
            <div v-if="showMore">
              <el-link
                type="primary"
                @click="handleCommonClick(data.href, data.query)"
                underline="never"
              >
                {{ data.moreText }}
              </el-link>
            </div>
          </div>
        </template>
        <component :is="$slots.default"></component>
      </el-card>
    </DefineTemplate>
    <DefineListTemplate v-slot="{ list, type, showTag = false }">
      <template v-if="!list?.length">
        <NoData />
      </template>
      <template v-else>
        <div
          v-for="(todo, index) of list"
          :key="todo.id"
          class="flex items-center text-sm h-6 mb-4 cursor-pointer hover:text-primary"
          @click="handleTodoClick(todo, type)"
          :class="index === list.length - 1 ? '!mb-0' : ''"
        >
          <el-tag
            :fit="false"
            v-if="showTag"
            :color="ETaskBgColors[todo.type]"
            type="primary"
            effect="dark"
            size="small"
            style="border: none; border-radius: 0"
            :style="{ color: ETaskColors[todo.type] }"
          >
            {{ ETaskType[todo.type] }}
          </el-tag>
          <div class="flex-1 min-w-1 text-ellipsis ml-1">{{ todo.title }}</div>
          <span class="text-xs ml-2 text-[#999]">
            {{ formatDateStr(todo.creatTime, 'YYYY-MM-DD') }}
          </span>
        </div>
      </template>
    </DefineListTemplate>
    <el-row :gutter="10">
      <el-col :span="17">
        <el-row>
          <el-col :span="24">
            <!-- 领导办件统计 -->
            <ReuseTemplate :data="departmentTaskCounts">
              <DepartmentTask />
            </ReuseTemplate>
          </el-col>

          <el-col class="mt-2" :span="24">
            <!-- 常用功能 -->
            <ReuseTemplate :data="commonFunction" bodyClass="h-[102px]">
              <div class="flex">
                <div
                  v-for="common of commonComputedList"
                  :key="common.id"
                  class="mr-[30px] pt-2 flex flex-col items-center cursor-pointer hover:text-primary"
                  @click="handleCommonClick(common.href, common.query)"
                >
                  <div class="w-[84px] flex justify-center items-center">
                    <img class="w-7" :src="common.icon" alt="" />
                  </div>
                  <p class="mt-4 text-sm text-center">{{ common.name }}</p>
                </div>
              </div>
            </ReuseTemplate>
          </el-col>
        </el-row>
      </el-col>
      <el-col :span="7">
        <ReuseTemplate
          :data="todoTask"
          :loading="todoLoading"
          :showMore="todoRes?.length"
          class="h-full"
        >
          <ReuseListTemplate :list="todoRes" :type="true" :showTag="true" />
        </ReuseTemplate>
      </el-col>
    </el-row>
    <RoleGuard :role="responsibleRoleGroup">
      <el-row class="mt-2" :gutter="10">
        <el-col :span="17">
          <el-row :gutter="10">
            <el-col :span="12">
              <!-- 办理中事件 -->
              <ReuseTemplate
                :loading="taskingLoading"
                :data="tasking"
                :showMore="taskingRes?.length"
                bodyClass="h-[322px] pt-1"
              >
                <ReuseListTemplate :list="taskingRes" />
              </ReuseTemplate>
            </el-col>
            <el-col :span="12">
              <ReuseTemplate
                :loading="taskingLoading"
                :data="taskTimeout"
                :showMore="timeoutRes?.length"
                bodyClass="h-[322px] pt-1"
              >
                <ReuseListTemplate :list="timeoutRes" />
              </ReuseTemplate>
            </el-col>
          </el-row>
        </el-col>
        <el-col :span="7">
          <!-- 已办理事件 -->
          <ReuseTemplate
            :data="finishedTask"
            :loading="taskingLoading"
            :showMore="finishedRes?.length"
            bodyClass="h-[320px] pt-1"
          >
            <ReuseListTemplate :list="finishedRes" />
          </ReuseTemplate>
        </el-col>
      </el-row>
    </RoleGuard>
    <RoleGuard :role="leaderRoleGroup">
      <el-row class="mt-2" :gutter="10">
        <el-col :span="17">
          <ReuseTemplate :data="implementationDecisions" bodyClass="h-[330px]">
            <!-- 决策落实 -->
            <ImplementationDecisions />
          </ReuseTemplate>
        </el-col>
        <el-col :span="7">
          <ReuseTemplate
            :data="importantEvents"
            :showMore="importantRes?.length"
            :loading="importantLoading"
            class="h-full"
          >
            <!-- 重点关注 -->
            <ReuseListTemplate :list="importantRes" />
          </ReuseTemplate>
        </el-col>
      </el-row>
    </RoleGuard>
    <el-row class="mt-2 pb-4" :gutter="10">
      <el-col :span="17">
        <ReuseTemplate
          v-if="userStore?.hasRoleCode(leaderRoleGroup)"
          :data="departmentDealLeader"
          :showMore="true"
          bodyClass="h-[260px]"
        >
          <DealCardsLeader />
        </ReuseTemplate>
        <ReuseTemplate v-else :data="departmentDeal" bodyClass="h-[260px]">
          <DepartmentDealCards />
        </ReuseTemplate>
      </el-col>
      <el-col :span="7">
        <ReuseTemplate :data="decisionCounts" bodyClass="h-[260px]">
          <DecisionCounts />
        </ReuseTemplate>
      </el-col>
    </el-row>
    <HandleEvents ref="handleEvents" @update="updateList" />
  </div>
</template>
<script setup lang="ts">
import { createReusableTemplate } from '@vueuse/core'
import { computed, ref, useTemplateRef } from 'vue'
import { useRouter } from 'vue-router'
import DepartmentTask from './components/DepartmentTask.vue'
import DepartmentDealCards from './components/DepartmentDealCards.vue'
import DecisionCounts from './components/DecisionCounts.vue'
import { ETaskBgColors, ETaskColors, ETaskType } from '../events/mine/util'
import HandleEvents from '@/components/events/HandleEvents.vue'
import { EDetailType } from '../application/typings'
import useFetch from '@/hooks/useFetch'
import {
  queryFocusMatter,
  queryMyPendingAuditData,
  queryProcessingMatters,
} from '@/api/home'
import { formatDateStr } from '@/plugins/date'
import NoData from '@/components/NoData.vue'
import finishedPic from '@/assets/icons/finished.png'
import checkPic from '@/assets/icons/check.png'
import followIcon from '@/assets/icons/follow-icon.png'
import driveIcon from '@/assets/icons/drive-icon.png'
import DealCardsLeader from './components/DealCardsLeader.vue'
import ImplementationDecisions from './components/ImplementationDecisions.vue'
import useUserStore from '@/stores/user'
import {
  EFocusStatus,
  EMatterStatus,
  EMatterTodoStatus,
} from '@/components/statusShow/util'
import RoleGuard from '@/components/dataPermission/RoleGuard.vue'
import {
  leaderRoleGroup,
  responsibleRoleGroup,
} from '@/components/dataPermission/util'

const router = useRouter()

const userStore = useUserStore()

const [DefineTemplate, ReuseTemplate] = createReusableTemplate()

const [DefineListTemplate, ReuseListTemplate] = createReusableTemplate()

const handleEvents = useTemplateRef<typeof HandleEvents>('handleEvents')

const departmentTaskCounts = ref({
  title: '领导批示交办事件统计',
  icon: 'back',
  moreText: '',
  href: '',
})

const commonFunction = ref({
  title: '常用功能',
  icon: 'gear-fill',
  moreText: '',
  href: '',
})

const todoTask = ref({
  title: '我的待办',
  icon: 'folder-fill',
  moreText: '更多',
  href: `/events/mine`,
  query: {
    status: EMatterTodoStatus['待办理'],
  },
})

const tasking = ref({
  title: '办理中责任件（正常推进）',
  icon: 'folder-fill',
  moreText: '更多',
  query: {
    status: EMatterStatus['正常推进'],
  },
  href: `/mission/follow`,
})

const taskTimeout = ref({
  title: '办理中责任件（已超时）',
  icon: 'folder-fill',
  moreText: '更多',
  query: {
    status: EMatterStatus['已超时'],
  },
  href: `/mission/follow`,
})

const finishedTask = ref({
  title: '已办责任件',
  icon: 'folder-fill',
  moreText: '更多',
  query: {
    status: EMatterStatus['已完成'],
  },
  href: `/mission/follow`,
})

const departmentDeal = ref({
  title: '部门发牌情况',
  icon: 'substack',
  moreText: '',
  href: '',
})

const departmentDealLeader = ref({
  title: '部门发牌情况',
  icon: 'substack',
  moreText: '更多',
  href: '/events/deal',
})

const importantEvents = ref({
  title: '重点关注',
  icon: 'substack',
  moreText: '更多',
  href: '/mission/follow',
  query: {
    importantFocus: EFocusStatus['是'],
  },
})

const implementationDecisions = ref({
  title: '决策落实',
  icon: 'substack',
  moreText: '更多',
  href: '/mission/follow',
})

const decisionCounts = ref({
  title: '决策落实办理统计',
  icon: 'substack',
  moreText: '',
  href: '',
})

// 常用功能列表
const commonComputedList = computed(() => {
  const list = [
    {
      id: 1,
      name: '我的已办',
      icon: finishedPic,
      href: '/events/mine',
      query: {
        status: EMatterTodoStatus['已办理'],
      },
    },
    {
      id: 2,
      name: '事项跟踪',
      icon: followIcon,
      href: '/mission/follow',
      query: {},
    },
  ]

  if (userStore.permissionRoleList && userStore.hasRoleCode(leaderRoleGroup)) {
    list.push(
      {
        id: 3,
        name: '部门办件查询',
        icon: checkPic,
        href: '/events/department-assign',
        query: {},
      },
      {
        id: 4,
        name: '驾驶舱',
        icon: driveIcon,
        href: '/big-screen',
        query: {},
      },
    )
  }

  return list
})

// 待办事项点击
function handleTodoClick(task: Record<string, any>, type?: boolean) {
  handleEvents?.value.show(
    task.type,
    task,
    type ? EDetailType.APPROVE : EDetailType.VIEW,
  )
}

async function updateList() {
  // 更新数据
  await execute()
}

// 常用功能点击
function handleCommonClick(href: string, query?: Record<string, any>) {
  router.push({
    path: href,
    query,
  })
}

// 分页获取数据参数
function generatePageParams(other: Record<string, any> = {}, pageSize = 8) {
  return {
    currentPage: 1,
    pageSize,
    query: {
      ...other,
    },
  }
}
const taskingRes = ref([])
const finishedRes = ref([])
const timeoutRes = ref([])
const {
  loading: todoLoading,
  execute,
  res: todoRes,
} = useFetch<Record<string, any>[]>(
  queryMyPendingAuditData,
  generatePageParams({
    status: EMatterTodoStatus['待办理'],
  }),
  true,
  true,
)

const { loading: taskingLoading, onFetchSuccess } = useFetch<
  Record<string, any>[]
>(
  queryProcessingMatters,
  generatePageParams({
    matterProcessingType: '',
  }),
  true,
  false,
)

onFetchSuccess((data) => {
  taskingRes.value = dealMatterData(data?.proceedNormallyMatters)
  timeoutRes.value = dealMatterData(data?.timeOutMatters)
  finishedRes.value = dealMatterData(
    data?.completedMatters,
    ETaskType['事项详情'],
  )
})

// 处理事项返回字段统一名称
function dealMatterData(data, type = ETaskType['事项办理']) {
  if (!data?.length) return []
  return data.map((item) => ({
    ...item,
    title: item.matterTitle,
    type,
    matterId: item.id,
    id: item.receiveId,
  }))
}

const { loading: importantLoading, res: importantRes } = useFetch<
  Record<string, any>[]
>(queryFocusMatter, generatePageParams(), true, true, (data) =>
  dealMatterData(data, ETaskType['事项详情']),
)
</script>
<style lang="scss" scoped>
.home-view {
  min-height: calc(100vh - 101px);
}

:deep(.card-hd) {
  padding: 24px 20px 16px;
  font-size: 16px !important;
  font-weight: 700;
  color: var(--body-font-color);
  border-bottom: none;
}

:deep(.el-card__body) {
  padding: 0 20px 22px;
}
</style>
